import type {ResponseData, ResponsePaginationData} from '@/utils/request';
import {SUCCESS_CODE} from '@/utils/request';
import type {RequestData} from '@ant-design/pro-table';
import type {
  AuthPermission,
  AuthPermissionAddItem,
  AuthPermissionEditItem,
  AuthPermissionTableListItem
} from '@/pages/System/Auth/AuthPermission/data';
import {request} from 'umi';

/**
 * 获取权限列表
 * @param params
 */
export async function queryAdminAccessList(
    params: Pagination & { name?: string },
): Promise<RequestData<AuthPermissionTableListItem>> {
  const res: ResponsePaginationData<AuthPermission> = await request('/sys/permission/page', {
    params: {
      current: params.current,
      size: params.pageSize,
      name: params.name,
    },
  });

  if (res?.code !== SUCCESS_CODE) {
    return {success: false, total: 0, data: []};
  }

  return {
    success: res.code === SUCCESS_CODE,
    total: res.data.total,
    data: res.data.list,
  };
}

/**
 * 创建一个权限
 * @param params
 */
export async function addAdminAccess(params: AuthPermissionAddItem) {
  const {name, code} = params;

  return request('/sys/permission/', {
    method: 'POST',
    data: {accessCode: code, name},
  });
}

/**
 * 获取单个权限字典详情
 * @param params
 */
export async function getPermission(params: { id: string }) {
  const res = await request(`/sys/permission/${params.id}`);
  if (res.code === SUCCESS_CODE) {
    return res.data;
  }
  return res;
}

/**
 * 修改权限条目
 * @param params
 */
export async function editPermission(params: AuthPermissionEditItem): Promise<ResponseData<AuthPermission>> {
  const {id} = params;
  return request(`/sys/permission/${id}`, {
    method: 'POST',
    data: params,
  });
}

/**
 * 删除权限字典
 * @param params
 */
export async function removePermission(params: AuthPermission) {
  const res = await request(`/sys/permission/${params.id}`, {method: 'DELETE'});
  if (res.code === SUCCESS_CODE) {
    return res.data;
  }
  return res;
}

